package vn.mycrm.server.dal;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import javax.jdo.Query;
import javax.jdo.Transaction;

import com.google.appengine.api.datastore.Key;

import vn.mycrm.client.model.LoaiCH;
import vn.mycrm.server.entity.AbstractEntityStatus;
import vn.mycrm.server.entity.LoaiCHEntity;

public class LoaiCHDAL extends AbstractDAL{	
	
	@SuppressWarnings("unchecked")
	public List<LoaiCH> getList(){
		try{
			Query query = pm.newQuery(LoaiCHEntity.class);
			query.setFilter("status == ENABLE");
			List<LoaiCHEntity> entities = (List<LoaiCHEntity>)query.execute();
			List<LoaiCH> dtos = new ArrayList<LoaiCH>();
			for(LoaiCHEntity e : entities)
				dtos.add(get(e));
			return dtos;
			
		}catch(Exception ex){
			logger.log(Level.SEVERE, ex.getMessage());
		}finally{
			pm.close();
		}
		return null;
	}
	
	public boolean add(LoaiCH dto){
		Transaction tx = pm.currentTransaction();
		try{			
			tx.begin();
			LoaiCHEntity lch = new LoaiCHEntity(dto);
			pm.makePersistent(lch);
			tx.commit();
			return true;
		}catch(Exception ex){
			logger.log(Level.SEVERE, ex.getMessage());
			return false;
		}finally{
			if(tx.isActive())
				tx.rollback();
			pm.close();
		}
		
	}
	
	public boolean update(LoaiCH dto){
		Transaction tx = pm.currentTransaction();
		try{			
			tx.begin();
			LoaiCHEntity lch = pm.getObjectById(LoaiCHEntity.class, dto.getKey());
			if(lch.update(dto))
				tx.commit();			
			return true;
		}catch(Exception ex){
			logger.log(Level.SEVERE, ex.getMessage());
			return false;
		}finally{
			if(tx.isActive())
				tx.rollback();			
			pm.close();
		}
	}
			
	public boolean update(Key key, AbstractEntityStatus status){
		Transaction tx = pm.currentTransaction();
		try{			
			tx.begin();
			LoaiCHEntity lch = pm.getObjectById(LoaiCHEntity.class, key);
			if(lch.getStatus() != status)
			{
				lch.setStatus(status);
				tx.commit();
			}
			return true;
		}catch(Exception ex){
			logger.log(Level.SEVERE, ex.getMessage());
			return false;
		}finally{
			if(tx.isActive())
				tx.rollback();			
			pm.close();
		}
	}
	
	public LoaiCH get(Key key)
	{
		try{
			LoaiCHEntity obj = pm.getObjectById(LoaiCHEntity.class, key);
			LoaiCH lch = get(obj);
			return lch;
		}catch(Exception ex){
			logger.log(Level.SEVERE, ex.getMessage());
		}finally{
			pm.close();
		}
		return null;
	}
	
	public LoaiCH get(LoaiCHEntity entity){
		LoaiCH dto = new LoaiCH();
		dto.setKey(entity.getKey());
		dto.setTen(entity.getTen());
		dto.setMota(entity.getMota());
		dto.setGhiChu(entity.getGhiChu());
		return dto;
	}
	
}
